package org.ehe.business.drawing.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.ehe.business.drawing.domain.DesignDrawing;
import org.ehe.business.drawing.domain.DesignDrawingFiles;
import org.ehe.business.drawing.domain.bo.DesignDrawingBo;
import org.ehe.business.drawing.domain.dto.BatchUploadDrawingInsertDTO;
import org.ehe.business.drawing.domain.dto.BatchUploadResultDTO;
import org.ehe.business.drawing.domain.dto.DesignDrawingDTO;
import org.ehe.business.drawing.domain.dto.PDFExtractInfoDTO;
import org.ehe.business.drawing.domain.vo.DesignDrawingVO;
import org.ehe.business.drawing.service.DesignDrawingFilesService;
import org.ehe.business.drawing.service.DesignDrawingService;
import org.ehe.business.drawing.service.PDFExtractorService;
import org.ehe.common.core.domain.R;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 设计图管理
 *
 * @author :zhangnn
 * @className :DesignDrawingController
 * @description: TODO
 * @date 2025-07-22 09:53:41
 */
@RestController
@RequestMapping("/drawing")
@RequiredArgsConstructor
public class DesignDrawingController {

    private final DesignDrawingService designDrawingService;
    private final PDFExtractorService pdfExtractorService;
    private final DesignDrawingFilesService designDrawingFilesService;

    /**
     * 分页列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @PostMapping("/page")
    public TableDataInfo<DesignDrawingVO> pageDrawings(@RequestBody DesignDrawingBo bo, PageQuery pageQuery) {
        return designDrawingService.pageDrawings(bo, pageQuery);
    }

    /**
     * 新增图纸
     *
     * @param dtos
     * @return
     */
    @SaCheckPermission("drawing:draw:add")
    @Log(title = "新增设计图纸", linkType = "drawing", businessType = BusinessType.INSERT, idField = "id", nameField = "name")
    @PostMapping("/add")
    public R<String> addDrawing(@RequestBody List<DesignDrawingDTO> dtos) {
        if (null == dtos.get(0).getSiteId()) {
            return R.fail("请先选择点位！");
        }
        designDrawingService.addDrawing(dtos);
        return R.ok("新增图纸成功");
    }

    /**
     * 编辑图纸
     *
     * @param dtos
     * @return
     */
    @SaCheckPermission("drawing:draw:edit")
    @Log(title = "修改设计图", linkType = "drawing", businessType = BusinessType.UPDATE, idField = "id", nameField = "name")
    @PutMapping("/edit")
    public R<Boolean> editDrawing(@RequestBody List<DesignDrawingDTO> dtos) {
        Boolean result = designDrawingService.editDrawing(dtos);
        return R.ok(result);
    }

    /**
     * 删除图纸
     *
     * @param id
     * @return
     */
    @SaCheckPermission("drawing:draw:remove")
    @Log(title = "删除设计图纸", linkType = "drawing", businessType = BusinessType.DELETE, nameField = "drawName")
    @DeleteMapping("/delete/{id}")
    public R<DesignDrawing> deleteDrawing(@PathVariable Long id) {
        DesignDrawing drawing = designDrawingService.getById(id);

        // 获取图纸列表
        List<DesignDrawingFiles> list = designDrawingFilesService.list(
                new LambdaQueryWrapper<DesignDrawingFiles>().eq(DesignDrawingFiles::getDrawId, id));
        if (list.size() > 0) {
            return R.fail("删除失败：请点击[查看]进行文件删除！", drawing);
        }
        Boolean result = designDrawingService.deleteDrawing(id);
        return R.ok(drawing);
    }

    @SaCheckPermission("drawing:draw:remove")
    @Log(title = "删除设计图纸文件", linkType = "drawing", businessType = BusinessType.DELETE, nameField = "drawName")
    @DeleteMapping("/deleteFile/{fId}")
    public R<DesignDrawingFiles> deleteDrawingFile(@PathVariable Long fId) {
        DesignDrawingFiles drawingFiles = designDrawingFilesService.getById(fId);
        designDrawingFilesService.removeById(drawingFiles);
        return R.ok(drawingFiles);
    }

    /**
     * 批量删除图纸信息
     *
     * @param ids
     * @return
     */
    @SaCheckPermission("drawing:draw:remove")
    @DeleteMapping("/batch-delete")
    public R<Boolean> batchDeleteDrawings(@RequestBody Long[] ids) {
        Boolean result = designDrawingService.batchDeleteDrawings(ids);
        return R.ok(result);
    }

    /**
     * 查看图纸详情
     *
     * @param id
     * @return
     */
    @SaCheckPermission("drawing:draw:view")
    @GetMapping("/detail/{id}")
    public R<DesignDrawingVO> getDrawingDetail(@PathVariable Long id) {
        DesignDrawingVO result = designDrawingService.getDrawingDetail(id);
        return R.ok(result);
    }

    /**
     * BOM提取
     *
     * @param id
     * @return
     */
    @PostMapping("/extract-bom/{id}")
    public R<Boolean> extractBom(@PathVariable Long id) {
        Boolean result = designDrawingService.extractBom(id);
        return R.ok(result);
    }

    /**
     * 检查图纸编码是否存在
     *
     * @param drawCode
     * @param excludeId
     * @return
     */
    @GetMapping("/check-code")
    public R<Boolean> checkDrawCode(@RequestParam String drawCode,
            @RequestParam(required = false) Long excludeId) {
        Boolean exists = designDrawingService.checkDrawCodeExists(drawCode, excludeId);
        return R.ok(exists);
    }

    /**
     * 生成图纸编码
     */
    @GetMapping("/buildDrawCode")
    public R<String> buildDrawCode() {
        String result = designDrawingService.buildDrawCode();
        return R.ok("获取图纸编码成功", result);
    }

    /**
     * PDF信息提取
     *
     * @param file PDF文件
     * @return 提取的信息
     */
    @PostMapping("/extract-pdf")
    public R<PDFExtractInfoDTO> extractPdfInfo(@RequestParam("file") MultipartFile file) {
        // 检查文件类型
        if (file.isEmpty()) {
            return R.fail("文件不能为空");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.toLowerCase().endsWith(".pdf")) {
            return R.fail("只支持PDF文件格式");
        }

        // 检查文件大小（限制100MB）
        if (file.getSize() > 100 * 1024 * 1024) {
            return R.fail("文件大小不能超过100MB");
        }

        try {
            PDFExtractInfoDTO result = pdfExtractorService.extractDrawingInfo(file);
            return R.ok("PDF信息提取成功", result);
        } catch (Exception e) {
            return R.fail("PDF信息提取失败：" + e.getMessage());
        }
    }

    /**
     * 图纸统计信息
     *
     * @return 统计数据
     */
    @GetMapping("/statistics")
    public R<Object> getDrawingStatistics() {
        Object result = designDrawingService.getDrawingStatistics();
        return R.ok("获取统计信息成功", result);
    }

    /**
     * 图纸搜索建议
     *
     * @param keyword 关键词
     * @return 搜索建议
     */
    @GetMapping("/search-suggestions")
    public R<Object> getSearchSuggestions(@RequestParam String keyword) {
        Object result = designDrawingService.getSearchSuggestions(keyword);
        return R.ok("获取搜索建议成功", result);
    }

    /**
     * 导出图纸清单
     *
     * @param bo 查询条件
     * @return 导出结果
     */
    @SaCheckPermission("drawing:draw:export")
    @PostMapping("/export")
    public R<String> exportDrawingList(@RequestBody DesignDrawingBo bo) {
        String result = designDrawingService.exportDrawingList(bo);
        return R.ok("导出成功", result);
    }

    /**
     * 批量上传图纸（异步）
     * 根据文件名自动创建点位并上传图纸
     * 文件名格式: SL01A-0900-0100-0001 震盘料斗支架.SLDDRW
     * 
     * @return 任务ID和初始状态
     */
    @SaCheckPermission("drawing:draw:batchUpload")
    @Log(title = "批量上传图纸", linkType = "drawing", businessType = BusinessType.INSERT)
    @PostMapping("/batch-upload")
    public R<BatchUploadResultDTO> batchUploadDrawings(@RequestBody BatchUploadDrawingInsertDTO dto) {

        Long projectId = dto.getProjectId();
        List<String> files = dto.getFiles();
        // 参数校验
        if (projectId == null) {
            return R.fail("项目ID不能为空");
        }

        if (files == null || files.isEmpty()) {
            return R.fail("请选择要上传的文件");
        }

        try {
            // 调用异步处理方法
            BatchUploadResultDTO result = designDrawingService.batchUploadDrawingsAsync(projectId, files);
            return R.ok("任务已创建，正在后台处理中，请稍后查询进度", result);
        } catch (Exception e) {
            return R.fail("创建上传任务失败: " + e.getMessage());
        }
    }

    /**
     * 查询批量上传任务进度
     * 
     * @param taskId 任务ID
     * @return 任务状态和进度
     */
    @GetMapping("/batch-upload/status/{taskId}")
    public R<BatchUploadResultDTO> getUploadTaskStatus(@PathVariable String taskId) {
        try {
            BatchUploadResultDTO result = designDrawingService.getUploadTaskStatus(taskId);
            return R.ok(result);
        } catch (Exception e) {
            return R.fail("查询任务状态失败: " + e.getMessage());
        }
    }
}
